<?php
namespace Zxf5115\Laravel\Kernel\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Zxf5115\Laravel\Kernel\Traits\QueryTrait;
use Zxf5115\Laravel\Kernel\Casts\DateTimeCast;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Zxf5115\Laravel\Dictionary\Services\DictionaryService;

/**
 * @author zhangxiaofei [<1326336909@qq.com>]
 * @dateTime 2025-09-10
 *
 * 基础模型类
 *
 * 提供所有模型的通用功能和配置
 */
abstract class Base extends Model
{
  use QueryTrait;

  /**
   * 数据库表名
   */
  protected $table = '';

  /**
   * 模型时间戳自动维护
   */
  public $timestamps = true;

  /**
   * 设置created_at、updated_at、$dates数组内容使用10位整型格式
   */
  protected $dateFormat = 'U';

  /**
   * 创建时间戳字段名称
   */
  const CREATED_AT = 'create_time';

  /**
   * 更新时间戳字段名称
   */
  const UPDATED_AT = 'update_time';

  /**
   * 转换属性类型
   * @var array
   */
  protected $casts = [
    'status' => 'integer',
    'create_time' => 'integer',
    'update_time' => 'integer',
  ];


  /**
   * 模型初始化
   *
   * @return [type]
   */
  protected static function booted() : void
  {
    static::creating(fn (self $model) => $model->setTimestampsOnCreate());
    static::updating(fn (self $model) => $model->setUpdatedTimestamp());
  }


  /**
   * 创建时设置时间戳
   *
   */
  protected function setTimestampsOnCreate(): void
  {
    $timestamp = Carbon::now()->timestamp;

    $this->create_time = $timestamp;
    $this->update_time = $timestamp;
  }


  /**
   * 更新时设置时间戳
   *
   */
  protected function setUpdatedTimestamp(): void
  {
    $this->update_time = Carbon::now()->timestamp;
  }


  /**
   * 数据状态访问器
   *
   * @return [type]
   */
  protected function status(): Attribute
  {
    return Attribute::make(
      get: fn (?int $value) => $this->resolveStatus('data_status', $value),
      set: fn ($value) => (int)$value
    );
  }


  /**
   * 创建时间戳访问器
   *
   * @return [type]
   */
  protected function createTime(): Attribute
  {
    return Attribute::make(
      get: fn ($value) => Carbon::parse($value)->tz('Asia/Shanghai')->format('Y-m-d H:i:s'),
    );
  }


  /**
   * 解析状态码为状态信息
   *
   * @param title $title 字典标题
   * @param int $code 状态代码
   * @return array 状态信息
   */
  public function resolveStatus(string $title, ?int $code) : array
  {
    if(is_null($code))
    {
      return '';
    }

    $statusMap = app(DictionaryService::class)->getCacheDataByTitle($title);

    return $statusMap[$code] ?? [];
  }
}
